package com.lizard.schedule.net.http.request;

import android.text.TextUtils;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.lizard.schedule.ScheduleApplication;
import com.lizard.schedule.log.ScheduleLog;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.net.http.consts.AppType;
import com.lizard.schedule.net.http.request.bean.base.BaseRequest;
import com.lizard.schedule.net.http.ssl.ExtHttpClientStack;
import com.lizard.schedule.net.http.ssl.ScheduleSslHelper;
import com.lizard.schedule.utils.DeviceUtil;
import com.lizard.schedule.utils.JniSecurityUtil;
import com.lizard.schedule.utils.JsonUtil;
import com.lizard.schedule.utils.ScheduleUtil;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求管理类
 */
public class HttpRequestManager<T> {

    private static HttpRequestManager instance;

    /**
     * 是否允许打印日志
     */
    private final boolean logEnable = true;

    /**
     * 基础参数中的tag内容
     */
    private int httpTag = 1;

    /**
     * 通用Http请求队列
     */
    private RequestQueue commonHttpRequestQueue;

    private HttpRequestManager() {
        init();
    }

    public static HttpRequestManager getInstance() {
        if (instance == null) {
            synchronized (HttpRequestManager.class) {
                if (instance == null) {
                    instance = new HttpRequestManager();
                }
            }
        }
        return instance;
    }

    /**
     * 全局初始化
     */
    public void init() {
        commonHttpRequestQueue = Volley.newRequestQueue(
                ScheduleApplication.applicationContext,
                new ExtHttpClientStack(ScheduleSslHelper.genSslHttpClient()));
        commonHttpRequestQueue.start();

    }

    /**
     * 发起请求
     *
     * @param listener
     */
    public void request(BaseRequest request, final HttpResponseListener<T> listener) {

        RequestAnnotationHelp requestAnnotationHelp = new RequestAnnotationHelp(request);

        HttpResponseListener mListener = new HttpResponseListener<T>() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if (logEnable) {
                    log("onErrorResponse " + volleyError.getMessage());
                }
                if (listener != null) {
                    listener.onErrorResponse(volleyError);
                }
            }

            @Override
            public void onResponse(T t) {
                if (listener != null) {
                    listener.onResponse(t);
                }
            }
        };

        // 基础参数设置
        setBaseParams(request);

        byte[] bodyByte = null;
        String bodyJson = JsonUtil.getGson().toJson(request, request.getClass());
        if (bodyJson != null) {
            if (logEnable) {
                log("post body json:" + bodyJson);
            }
            try {
                bodyByte = bodyJson.getBytes(HttpRequest.ENCODING);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        HttpRequest httpRequest = new HttpRequest(requestAnnotationHelp.getMethod(),
                ScheduleUtil.isDebuggable() ? requestAnnotationHelp.getDebugUrl() : requestAnnotationHelp.getUrl(),
                bodyByte,
                getBaseHeaders(),
                requestAnnotationHelp.getResponseClazz(),
                mListener);

        // 添加到请求队列
        commonHttpRequestQueue.add(httpRequest);
    }

    /**
     * 基础参数设置
     *
     * @param request
     */
    private void setBaseParams(BaseRequest request) {
        request.setSystemTime(System.currentTimeMillis());
        if (TextUtils.isEmpty(request.getUsername())) {
            request.setUsername(TextUtils.isEmpty(AccountManager.getInstance().getUsername()) ? "" : AccountManager.getInstance().getUsername());
        }
        request.setVersionCode(ScheduleUtil.getVersionCode());
        request.setAppType(AppType.ANDROID);
        request.setImei(DeviceUtil.getImei());
        request.setImsi(DeviceUtil.getImsi());
        request.setTag("" + (httpTag++));
        request.setToken(TextUtils.isEmpty(AccountManager.getInstance().getToken()) ? null : AccountManager.getInstance().getToken());
        // 签名
        String sign = JniSecurityUtil.getSign(ScheduleApplication.applicationContext, JsonUtil.getGson().toJson(request, request.getClass()));
        request.setSign(sign);
    }

    private Map<String, String> getBaseHeaders() {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "*/*");
        headers.put("Content-Type", "application/json");
        return headers;
    }

    /**
     * 打印日志
     *
     * @param log
     */
    private void log(String log) {
        if (logEnable) {
            if (log != null) {
                ScheduleLog.v(HttpRequest.TAG_HTTP_REQUEST, log);
            }
        }
    }
}
